// app.js
import Observer from './utils/observer'
import {
  checkUpdateVersion
} from './utils/index'
import {
  userDetail,
  loginByCode,
} from "./utils/api/index"
const observer = new Observer();
App({
  globalData: {
    statusBarHeight: 0,
    tabbarHeight: 0, // 底部tabbar 高度
    userCount: {
      ecouponVerifiLength: 0,
      verifyGroupLength: 0
    },
    cityObj: {
      codeid: 11,
      cityname: "北京"
    },
    userInfo: null, // 用户基础信息
  },
  onLaunch(options) {
    observer.Observe(this.globalData);
    const _this = this;
    // 获取设备信息
    wx.getSystemInfo({
      success(res) {
        _this.globalData.statusBarHeight = res.statusBarHeight
        let lift = res.screenHeight - res.safeArea.bottom
        let tabbarHeight = Number(lift) + 50;
        _this.globalData.tabbarHeight = tabbarHeight;
      }
    })
    let accountInfo = wx.getAccountInfoSync();
    let version = accountInfo.miniProgram.version; // 1.0.0 小程序版本号
    _this.globalData._ffl_version = version;
  },
  watch(key, fn) {
    observer.makeWatcher(key, this.globalData, fn);
  },
  onShow() {
    // 判断用户是否更新小程序
    checkUpdateVersion();
    this.queryInfo();
  },
  // 更新登录信息
  queryInfo() {
    return new Promise((resolve, reject) => {
      const token = this.getToken();
      if (!token) {
        wx.login({
          success: async (res) => {
            const response = await loginByCode({
              code: res.code,
            })
            const {
              data
            } = response;
            wx.setStorageSync('token', data.accessToken);
            wx.setStorageSync('userInfo', data);
            this.setGlobalData('userInfo', data);
            resolve()
          },
        })
      }
    })
  },
  // 获取缓存Token
  getToken() {
    const token = wx.getStorageSync("token") || "";
    return token;
  },
  // 设置全局变量
  setGlobalData(key, value) {
    this.globalData[key] = value;
  },
  // 获取全局变量
  getGlobalData(key) {
    return this.globalData[key];
  },
  // 判断用户是否已登录刷新登录
  hasPermi() {
    return new Promise((resolve, reject) => {
      let token = wx.getStorageSync("token");
      if (token) {
        resolve();
      } else {
        wx.clearStorageSync();
        this.queryInfo().then(() => {
          resolve()
        })
      }
    })
  },
  /**
   * 用户个人信息缓存更新
   * */
  async setUserCount() {
    const token = this.getToken()
    if (token) {
      try {
        const res = await userDetail();
        wx.setStorageSync('userInfo', res.data);
      } catch (error) {}
    }
  },
})